package edu.dlust.trading_platform;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.json.JSONArray;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import edu.dlust.trading_platform.DataBase.MongoDB;
import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBean.CommentBean;
import edu.dlust.trading_platform.DataBean.GoodsBean;
import edu.dlust.trading_platform.DataBean.userdata;
import edu.dlust.trading_platform.adapter.CommentAdapter;
import edu.dlust.trading_platform.adapter.HomePageAdapter;

public class GoodsDetailsActivity extends AppCompatActivity {
    private String goodsId,UID;
    private ImageView goods_img,back,head;
    private TextView username, contact, fenlei, price, chengse, phone, goods, sent,text;
    private EditText Ecomment;
    private Button Bcumment,buy;
    private ListView listview;
    private List<CommentBean> list;
    private CommentAdapter adapter;
    private LinearLayout details_buttons,details_text;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);

        goodsId = getIntent().getStringExtra("goodsId");
        init();
        insert();
        findData();
        back = findViewById(R.id.detail_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GoodsDetailsActivity.this.finish();
            }
        });
        Buy();
        refresh();
    }

    private void init() {
        goods_img = findViewById(R.id.imageView_goods);
        username = findViewById(R.id.textView_username);
        contact = findViewById(R.id.textView_contact);
        fenlei = findViewById(R.id.details_fenlei);
        price = findViewById(R.id.details_price);
        chengse = findViewById(R.id.details_chengse);
        phone = findViewById(R.id.details_phone);
        goods = findViewById(R.id.textView_goods_detail);
        sent = findViewById(R.id.details_sent);
        details_buttons = findViewById(R.id.details_buttons);
        details_text = findViewById(R.id.details_text);
        text = findViewById(R.id.TV_details_text);
        head = findViewById(R.id.imageView_avatar);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Connection con = MySQL.getConnection();
                    String sql = "SELECT l.UName, g.Uid, g.Classification, g.Price, g.Fineness, l.Phone, g.Content, g.Type, g.Image AS GImage, l.Image AS LImage, l2.UName AS Buyer_UName FROM GOODS g INNER JOIN LOGINID l ON g.Uid = l.Uid LEFT JOIN LOGINID l2 ON g.Buyer = l2.Uid WHERE g.id = ?;";
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setString(1, goodsId);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (rs.getString("Buyer_UName") == null){
                                        username.setText(rs.getString("UName"));
                                        UID = rs.getString("Uid");
                                        contact.setText(UID);
                                        fenlei.setText("商品分类： "+rs.getString("Classification"));
                                        price.setText("价格： "+rs.getString("Price")+"￥");
                                        chengse.setText("物品成色： "+rs.getString("Fineness"));
                                        phone.setText("联系方式： "+rs.getString("Phone"));
                                        sent.setText("发货方式："+rs.getString("Type"));
                                        goods.setText(rs.getString("Content"));
                                        byte[] Gimage = rs.getBytes("GImage");
                                        if (Gimage != null) {
                                            Bitmap bitmap = BitmapFactory.decodeByteArray(Gimage, 0, Gimage.length);
                                            goods_img.setImageBitmap(bitmap);
                                        } else {
                                            goods_img.setImageResource(R.drawable.noimage);
                                        }
                                        byte[] Limage = rs.getBytes("LImage");
                                        if (Limage != null) {
                                            Bitmap bitmap = BitmapFactory.decodeByteArray(Limage, 0, Limage.length);
                                            head.setImageBitmap(bitmap);
                                        } else {
                                            head.setImageResource(R.drawable.user);
                                        }

                                    }else {
                                        details_buttons.setVisibility(View.GONE);
                                        text.setText("该商品已经被"+rs.getString("Buyer_UName")+"购买啦！");
                                        details_text.setVisibility(View.VISIBLE);
                                        username.setText(rs.getString("UName"));
                                        UID = rs.getString("Uid");
                                        contact.setText(UID);
                                        fenlei.setText("商品分类： "+rs.getString("Classification"));
                                        price.setText("价格： "+rs.getString("Price")+"￥");
                                        chengse.setText("物品成色： "+rs.getString("Fineness"));
                                        phone.setText("联系方式： "+rs.getString("Phone"));
                                        sent.setText("发货方式："+rs.getString("Type"));
                                        goods.setText(rs.getString("Content"));
                                        byte[] Gimage = rs.getBytes("GImage");
                                        if (Gimage != null) {
                                            Bitmap bitmap = BitmapFactory.decodeByteArray(Gimage, 0, Gimage.length);
                                            goods_img.setImageBitmap(bitmap);
                                        } else {
                                            goods_img.setImageResource(R.drawable.noimage);
                                        }
                                        byte[] Limage = rs.getBytes("LImage");
                                        if (Limage != null) {
                                            Bitmap bitmap = BitmapFactory.decodeByteArray(Limage, 0, Limage.length);
                                            head.setImageBitmap(bitmap);
                                        } else {
                                            head.setImageResource(R.drawable.user);
                                        }
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GoodsDetailsActivity.this, "查询出现问题或商品已被删除", Toast.LENGTH_SHORT).show();
                                GoodsDetailsActivity.this.finish();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void insert(){
        Ecomment = findViewById(R.id.editText_comment);
        Bcumment = findViewById(R.id.button_comment);

        Bcumment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String things = Ecomment.getText().toString();
                LocalDateTime currentTime = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedTime = currentTime.format(formatter);
                MongoDB mongoDB = new MongoDB();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mongoDB.insert(goodsId,things, userdata.getUid(),userdata.getName(),formattedTime);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(GoodsDetailsActivity.this, "评论成功!", Toast.LENGTH_SHORT).show();
                                    Ecomment.setText("");
                                    findData();
                                }
                            });
                        } catch (Exception e) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(GoodsDetailsActivity.this, "评论失败!", Toast.LENGTH_SHORT).show();
                                }
                            });
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    private void findData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<CommentBean> data = show();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        List(data);
                    }
                });
            }
        }).start();
    }

    private List<CommentBean> show(){
        List<CommentBean> lists = new ArrayList<>();
                try {
                    MongoClient mongoClient = MongoClients.create("mongodb://frp.lsakura.top:8003");
                    MongoDatabase database = mongoClient.getDatabase("android");
                    MongoCollection<Document> collection = database.getCollection("message");

                    // 构建查询条件
                    Bson filter = Filters.eq("GoodsId", goodsId);

                    // 查询文档
                    FindIterable<Document> docs = collection.find(filter);


                    for (Document doc : docs) {
                        CommentBean commentBean = new CommentBean();
                        JSONObject all = new JSONObject(doc.toJson());
                        String message = all.getString("message");
                        String UName = all.getString("UName");
                        String time = all.getString("time");

                        commentBean.setMessage(message);
                        commentBean.setUName(UName);
                        commentBean.setTime(time);

                        lists.add(commentBean);
                    }

                    mongoClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return lists;
            }

    private void List(List<CommentBean> data){

        listview = findViewById(R.id.listView_comments);
        if (list != null) {
            list.clear();
        }
        list = data;
        adapter = new CommentAdapter(this, list);
        listview.setAdapter(adapter);
    }

    private void Buy(){
        buy = findViewById(R.id.button_buy);
        buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UID.equals(userdata.getUid())){
                    Toast.makeText(GoodsDetailsActivity.this, "自己不能购买自己的的商品！", Toast.LENGTH_SHORT).show();
                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(GoodsDetailsActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("您确认要购买吗？此操作不可逆！");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                               String str = "SELECT Buyer FROM GOODS WHERE id = ?;";
                               Connection con = MySQL.getConnection();
                                PreparedStatement ps = con.prepareStatement(str);
                                ps.setString(1, goodsId);
                                ResultSet rs = ps.executeQuery();
                                if (rs.next()) {
                                    String Buyer = rs.getString("Buyer");

                                    if(Buyer == null){
                                        String str2 = "UPDATE GOODS SET Buyer = ? WHERE id = ?;";
                                        PreparedStatement ps2 = con.prepareStatement(str2);
                                        ps2.setString(1,userdata.getUid());
                                        ps2.setString(2,goodsId);
                                        int rowsUpdated = ps2.executeUpdate();
                                        if (rowsUpdated > 0) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(GoodsDetailsActivity.this, "购买成功，请前往我的购买查看卖家消息", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                            GoodsDetailsActivity.this.finish();
                                        }else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(GoodsDetailsActivity.this, "购买失败", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                        }
                                    }else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(GoodsDetailsActivity.this, "该商品已经被人购买啦！", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                }else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(GoodsDetailsActivity.this, "商品可能已被删除，请刷新界面！", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                                con.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                }
            }
        });
    }
    private void refresh(){
        swipeRefreshLayout = findViewById(R.id.details_swipeRefreshLayout);

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                refreshData();
            }
        });

        // 初始化数据
        refreshData();
    }
    private void refreshData() {
        findData();
        swipeRefreshLayout.setRefreshing(false);
    }
}